package cn.thoughtworks.school.controllers;

import cn.thoughtworks.school.entities.HomeworkQuiz;
import cn.thoughtworks.school.entities.HomeworkSubmission;
import cn.thoughtworks.school.entities.Stack;
import cn.thoughtworks.school.handlers.BusinessException;
import cn.thoughtworks.school.repositories.HomeworkSubmissionRepository;
import cn.thoughtworks.school.requestParams.HomeworkSubmissionParam;
import cn.thoughtworks.school.services.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

import static cn.thoughtworks.school.services.Utils.readFileToString;

@RestController
@RequestMapping(value = "/api/single-stack-programming-quiz-submissions")
@Slf4j
public class SingleStackProgrammingQuizSubmissionController {

    @Value("${jenkins.callbackHost}")
    private String jenkinsCallbackHost;
    @Autowired
    SingleStackProgrammingSubmissionService singleStackProgrammingSubmissionService;
    @Autowired
    HomeworkQuizService homeworkQuizService;
    @Autowired
    StackService stackService;
    @Autowired
    JenkinsService jenkinsService;
    @Autowired
    AmazonClientService amazonClientService;
    @Autowired
    private HomeworkSubmissionRepository homeworkSubmissionRepository;

    @PostMapping
    @Transactional
    public ResponseEntity createSubmission(@RequestBody HomeworkSubmissionParam param) throws BusinessException, IOException {
        HomeworkSubmission homeworksubmission = singleStackProgrammingSubmissionService.save(param);
        HomeworkQuiz homeworkQuiz = homeworkQuizService.getHomeworkQuiz(param.getQuizId());
        Stack stack = stackService.getStack(homeworkQuiz.getStackId());
        String callbackUrl = String.format("%s/api/single-stack-programming-quiz-submissions/%s",
                jenkinsCallbackHost, homeworksubmission.getId());
        String answerUrl = String.format("%s/api/single-stack-programming-quiz/%s/answerFile",
                jenkinsCallbackHost, homeworkQuiz.getId());
        HttpStatus httpStatus = jenkinsService.triggerSingleStackProgrammingQuizSubmissionJob(
                param.getUserAnswerRepo(),
                param.getBranch(),
                callbackUrl,
                stack.getImage(),
                answerUrl
        );
        if (httpStatus.value() != 201) {
            throw new BusinessException("jenkins server error!");
        }
        return new ResponseEntity<>(homeworksubmission, httpStatus);
    }

    @PostMapping(value = "/{id}")
    public ResponseEntity updateSubmission(@PathVariable Long id
            , @RequestParam(required = false) Integer status
            , @RequestParam(required = false) String msg
            , @RequestParam(value = "job_msg", required = false) MultipartFile job_msg
            , @RequestParam(required = false) Long buildNumber) throws BusinessException {
        HomeworkSubmission submission = singleStackProgrammingSubmissionService.getSubmission(id);
        submission.setStatus(status);
        submission.setBuildNumber(buildNumber);
        String result = msg.concat("\n").concat(readFileToString(job_msg));
        submission.setResult(result);
        log.info("HomeworkQuiz state message info: " + job_msg);
        singleStackProgrammingSubmissionService.save(submission);
        return new ResponseEntity(HttpStatus.OK);
    }

    @GetMapping(value = "/{id}")
    public ResponseEntity getSubmission(@PathVariable Long id) throws BusinessException {
        HomeworkSubmission submission = singleStackProgrammingSubmissionService.getSubmission(id);
        return new ResponseEntity<>(submission, HttpStatus.OK);
    }

    @GetMapping(value = "/{userId}/{assignmentId}/{quizId}")
    public ResponseEntity getAllSubmission(@PathVariable Long userId
            , @PathVariable Long assignmentId
            , @PathVariable Long quizId
            , @RequestParam(value = "page", defaultValue = "0") int page
            , @RequestParam(value = "size", defaultValue = "10") int size) {
        List<HomeworkSubmission> list = singleStackProgrammingSubmissionService.getAllSubmission(
                userId, assignmentId, quizId, page, size);
        return new ResponseEntity<>(list, HttpStatus.OK);
    }

    @PutMapping("{id}/status")
    public ResponseEntity updateStatus(@PathVariable Long id,
                                       @RequestParam(value = "message", required = false) MultipartFile message) throws BusinessException, IOException {
        HomeworkSubmission homeworkSubmission = homeworkSubmissionRepository.findById(id).orElseThrow(() ->
                new BusinessException("提交不存在"));
        System.out.println(message.getBytes().toString());
        String description = readFileToString(message);
        System.out.println(description);
        homeworkSubmission.setResult(description);
        homeworkSubmissionRepository.save(homeworkSubmission);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }
}
